package com.gzz.orchid.context.domain.rbac.entity;

import com.gzz.orchid.common.core.util.EncryptUtil;
import com.gzz.orchid.common.core.util.I18nUtil;
import com.gzz.orchid.context.infrastructure.definition.Status;
import com.gzz.orchid.context.infrastructure.persistence.entity.sys.SysUserPo;
import lombok.Data;

/**
 * @author higmd
 */
@Data
public class UserDo {
    private Long id;
    /**
     * 用户名 user_name
     */
    private String userName;
    /**
     * 密码 passwd
     */
    private String passwd;
    /**
     * 密码盐 salt
     */
    private String salt;

    /**
     * 昵称 pet_pame
     */
    private String petName;
    /**
     * 登录白名单 allow_ipaddr
     */
    private String allowIpaddr;
    /**
     * 登录黑名单 deny_ipaddr
     */
    private String denyIpaddr;
    /**
     * 状态 status
     */
    private Status status;

    public static UserDo convertFrom(SysUserPo po) {
        UserDo udo = new UserDo();
        udo.setId(po.getId());
        udo.setUserName(po.getUserName());
        udo.setPasswd(po.getPasswd());
        udo.setSalt(po.getSalt());
        udo.setPetName(po.getPetName());
        udo.setAllowIpaddr(po.getAllowIpaddr());
        udo.setDenyIpaddr(po.getDenyIpaddr());
        udo.setStatus(Status.parse(po.getStatus()));
        return udo;
    }

    public void changePassword(String newPasswd, String oldPasswd) {
        if (this.passwd.equals(EncryptUtil.hashEncrypt(oldPasswd, this.salt)))
            throw new IllegalArgumentException(I18nUtil.ofMessage("旧密码错误"));
        this.salt = EncryptUtil.randomSalt();
        this.passwd = EncryptUtil.hashEncrypt(newPasswd, this.salt);

    }

    public void resetPassword() {
        this.salt = EncryptUtil.randomSalt();
        this.passwd = EncryptUtil.hashEncrypt("123456", this.salt);

    }
}
